package org.kd.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.kd.config.ApplicationContextRegister;
import org.kd.model.Emp;
import org.kd.model.DTO.EmpDTO;
import org.kd.service.EmpBTOService;
import org.kd.service.EmpService;

public class AuthRealm extends AuthorizingRealm{


	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Set<String> perms = new HashSet<String>();
		Object principal = principals.getPrimaryPrincipal();
        if (principal instanceof Emp) {
        	Emp emp = (Emp) principal;
        	EmpBTOService  empService = ApplicationContextRegister.getBean(EmpBTOService.class);
        	perms = empService.queryMenu(emp.getId());
        }
	
		//权限标识放入令牌中
		info.setStringPermissions(perms);
		
		return info;
	}

	/**
     * 验证用户身份
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		    UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
		    String password = new String((char[]) token.getCredentials());
		    EmpDTO model = new EmpDTO();
		    model.setUsername(utoken.getUsername());
	        EmpService  empService = ApplicationContextRegister.getBean(EmpService.class);
	        Emp param = empService.queryByParam(model);
	        
	        // 账号不存在
			if (param == null) {
				throw new UnknownAccountException("账号或密码不正确");
			}

			// 密码错误
			if (!password.equals(param.getPassword())) {
				throw new IncorrectCredentialsException("账号或密码不正确");
			}

	        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(param, password, getName());  //放入shiro.调用CredentialsMatcher检验密码
			return info;
	}

}
